// cart.ts
Component({
  data: {
    cartItems: [],
    selectAll: false,
    totalPrice: 0,
    selectedCount: 0
  },

  methods: {
    // 加载购物车
    loadCart() {
      const cart = wx.getStorageSync('cart') || []
      this.setData({ 
        cartItems: cart,
        selectAll: cart.length > 0 && cart.every((item: any) => item.selected)
      })
      this.calculateTotal()
    },

    // 计算总价
    calculateTotal() {
      const { cartItems } = this.data
      const selectedItems = cartItems.filter((item: any) => item.selected)
      const totalPrice = selectedItems.reduce((sum: number, item: any) => sum + item.price * item.quantity, 0)
      const selectedCount = selectedItems.reduce((sum: number, item: any) => sum + item.quantity, 0)
      
      this.setData({
        totalPrice,
        selectedCount
      })
    },

    // 切换商品选择
    toggleSelect(e: any) {
      const id = e.detail.value[0]
      const { cartItems } = this.data
      
      const item = cartItems.find((item: any) => item.id === parseInt(id))
      if (item) {
        item.selected = !item.selected
        this.setData({ cartItems })
        wx.setStorageSync('cart', cartItems)
        this.calculateTotal()
        this.updateSelectAll()
      }
    },

    // 全选/取消全选
    toggleSelectAll() {
      const { selectAll, cartItems } = this.data
      const newSelectAll = !selectAll
      
      cartItems.forEach((item: any) => {
        item.selected = newSelectAll
      })
      
      this.setData({
        cartItems,
        selectAll: newSelectAll
      })
      
      wx.setStorageSync('cart', cartItems)
      this.calculateTotal()
    },

    // 更新全选状态
    updateSelectAll() {
      const { cartItems } = this.data
      const selectAll = cartItems.length > 0 && cartItems.every((item: any) => item.selected)
      this.setData({ selectAll })
    },

    // 增加数量
    increaseQuantity(e: any) {
      const id = e.currentTarget.dataset.id
      const { cartItems } = this.data
      
      const item = cartItems.find((item: any) => item.id === id)
      if (item) {
        item.quantity += 1
        this.setData({ cartItems })
        wx.setStorageSync('cart', cartItems)
        this.calculateTotal()
      }
    },

    // 减少数量
    decreaseQuantity(e: any) {
      const id = e.currentTarget.dataset.id
      const { cartItems } = this.data
      
      const item = cartItems.find((item: any) => item.id === id)
      if (item && item.quantity > 1) {
        item.quantity -= 1
        this.setData({ cartItems })
        wx.setStorageSync('cart', cartItems)
        this.calculateTotal()
      }
    },

    // 删除商品
    deleteItem(e: any) {
      const id = e.currentTarget.dataset.id
      const { cartItems } = this.data
      
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            const newCart = cartItems.filter((item: any) => item.id !== id)
            this.setData({ cartItems: newCart })
            wx.setStorageSync('cart', newCart)
            this.calculateTotal()
            this.updateSelectAll()
          }
        }
      })
    },

    // 结算
    checkout() {
      const { cartItems, selectedCount } = this.data
      
      if (selectedCount === 0) {
        wx.showToast({
          title: '请选择商品',
          icon: 'none'
        })
        return
      }

      const selectedItems = cartItems.filter((item: any) => item.selected)
      wx.showModal({
        title: '确认购买',
        content: `共${selectedCount}件商品，总计¥${this.data.totalPrice}`,
        success: (res) => {
          if (res.confirm) {
            // 模拟购买流程
            wx.showLoading({ title: '处理中...' })
            setTimeout(() => {
              wx.hideLoading()
              
              // 保存购买记录
              const purchaseHistory = wx.getStorageSync('purchaseHistory') || []
              purchaseHistory.push({
                id: Date.now(),
                items: selectedItems,
                totalPrice: this.data.totalPrice,
                date: new Date().toLocaleString(),
                status: 'paid'
              })
              wx.setStorageSync('purchaseHistory', purchaseHistory)
              
              // 清空购物车
              const newCart = cartItems.filter((item: any) => !item.selected)
              wx.setStorageSync('cart', newCart)
              
              this.setData({ cartItems: newCart })
              this.calculateTotal()
              
              wx.showToast({
                title: '购买成功',
                icon: 'success',
                complete: () => {
                  wx.navigateTo({
                    url: '/pages/my-products/my-products'
                  })
                }
              })
            }, 1500)
          }
        }
      })
    },

    // 去购物
    goToProducts() {
      wx.switchTab({
        url: '/pages/products/products'
      })
    }
  },

  lifetimes: {
    attached() {
      // 检查登录状态
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      const token = wx.getStorageSync('token')
      
      if (!isLoggedIn || !token) {
        // 使用redirectTo避免返回循环
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return
      }
      this.loadCart()
    }
  },

  pageLifetimes: {
    show() {
      this.loadCart()
    }
  }
})